from nest.path.iterator import PathIterator
from nest.path.exception import PathError
from nest.path import Path


class PathParser(object):

    def __init__(self, tree, path):
        self._tree = tree
        self._path = path
        self.path_head = None
        self.path_tail = None

    def get_iterator(self):
        return PathIterator(self)

    def parse(self):
        raise PathError()

    def is_parsed(self):
        '''
        Tell if parsing required.
        '''
        if isinstance(self._path, Path):
            # Is already a parsed instance.
            return False
        if not self.path_head or not self.path_tail:
            return True
        return False

    def __assert_parsing(self):
        if self.is_parsed():
            self.parse()

    def pop_head(self):
        self.__assert_parsing()
        self._path = self.path_tail
        head = self.path_head
        self.path_head = None
        self.path_tail = None
        return head

    def get_head(self):
        self.__assert_parsing()
        return self.path_head

    def get_tail(self):
        self.__assert_parsing()
        return self.path_tail

    def copy(self):
        return self.__class__(self._tree, self._path)

